<?php
namespace app\admin\service;

use app\api\controller\ApiXwql;
use app\api\controller\WeChat;
use think\facade\Cache;
use think\facade\Db;

class ConfigService
{

    public static function getVersion()
    {
        $version = Cache('version');
        if (empty($version)) {
            $version = sysconfig('site', 'site_version');
            cache('site_version', $version);
            Cache::set('version', $version, 3600);
        }
        return $version;
    }

    public static function getViewCount($location_id,$isTownship){
        //$count = Db::name('system_config')->where([['name','=','total_viewcounts']])->value('value');
        $where = [];
        $isTownship && $where[] = ['township','=',$location_id];
        $count = Db::name('xwql_visits')->field('id')->where($where)->count();
        return $count;
    }

    public static function getPersonCount($location_id,$isTownship){
        $where = [
            ['village','<>',0],
            ['status','=',1]
        ];
        $isTownship && $where[] = ['township','=',$location_id];
        $count = Db::name('wx_user')->field('id')->where($where)->count();
        return $count;
    }

    public static function addViewCount($location_id){
        //$daoAdd = Db::name('system_config')->where([['name','=','total_viewcounts']])->inc('value')->update();
        $cache_key=input('cache_key');
        $model = new ApiXwql();
        if($model->isLogin($cache_key)){
            $openId = Cache::get('api_open_id_'.$cache_key);
            $uid = Db::name('wx_user')->where(['open_id'=>$openId])->value('id');

            $model1 = new WeChat();
            $model1->addVisits($uid,$location_id);
        }

        $where = [];
        $isTownship = \app\api\service\Common::checkIsTownship($location_id);
        $isTownship && $where[] = ['township','=',$location_id];
        $view_count = Db::name('xwql_visits')->where($where)->count();
        return $view_count;
    }

    public static function getIsWatch(){
        $isWatch = 0; //默认不显示
        $cache_key=input('cache_key');
        $model = new ApiXwql();
        if($model->isLogin($cache_key)){
            //授权且未观看显示
            $openId = Cache::get('api_open_id_'.$cache_key);
            $isWatch = Db::name('wx_user')->where(['open_id'=>$openId])->value('is_watch');
            if ($isWatch == 2){
                $isWatch = 0;
            }
        }
        return $isWatch;
    }

    public static function setIsWatch(){
        $cache_key=input('cache_key');
        $model = new ApiXwql();
        if($model->isLogin($cache_key)){
            $openId = Cache::get('api_open_id_'.$cache_key);
            $isWatch = Db::name('wx_user')->where(['open_id'=>$openId])->value('is_watch');
            if ($isWatch == 1){
                //未观看，展示视频
                //更新观看状态为已观看
                Db::name('wx_user')->where(['open_id'=>$openId])->update(['is_watch'=>2]);
            }
        }
        return true;
    }
}